import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import path from 'path'
import fsPromises from 'fs/promises'

export function checkCustomRuleDir(customRuleDir?: string): string{
    step.info(`customRuleDir=${customRuleDir}`)
    if (customRuleDir == undefined){
        throw new Error(`customRuleDir is required when useCustomRule is true`)
    }
    if(path.isAbsolute(customRuleDir) || customRuleDir.includes('..')){
        throw new Error(`customRuleDir ${customRuleDir} is invalid. It should be a relative path without parent directory references.`)
    }
    const stat = fs.statSync(customRuleDir)
    if (stat.isFile()) {
        throw new Error(`customRuleDir ${customRuleDir} is not a directory`)
    }
    return customRuleDir
}

export async function setDependentFiles(targetDir: string){
    const currentDir = __dirname
    const copyList = ['diff','plugin-base.jar']
    for (const item of copyList) {
        copyDependency(path.join(currentDir,item), path.join(targetDir,item))
    }
    step.debug(`set permission for diff to 755`)
    fs.chmodSync(path.join(targetDir,'diff'), 0o755)

    try {
        const destPath = await step.tool.extract(path.join(currentDir, 'p3c-2.2.1.tgz'), targetDir)
        step.debug(`p3c-2.2.1.tgz was extracted to ${destPath}`)
    }catch (e){
        throw new Error(`failed to extract p3c-2.2.1.tgz to ${targetDir}: ${e}`)
    }
}


export function copyDependency(source: string, target: string) {
    step.debug(`copy ${source} to ${target}`)
    // 检查目标文件是否存在
    if (fs.existsSync(target)) {
        step.debug(`remove ${target}`)
        fs.unlinkSync(target);
    }
    fs.copyFileSync(source, target)
}

export async function readHtmlFile(filePath: string): Promise<string> {
    try {
        const data = await fsPromises.readFile(filePath, 'utf-8')
        return data
    } catch (error) {
        step.error(`Error reading file ${filePath}`)
        throw error
    }
}


